#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

void Usage(string proc)
{
    cout <<"Usage: " << "+ip+port" << endl;
}
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        cerr << "socket create error" << endl;
        exit(1);
    }
    cout << "socket create success" << endl;

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = INADDR_ANY;

    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if(sockfd < 0)
    {
        cerr << "connect create error" << endl;
        exit(2);
    }
    cout << "connect create success" << endl;

    while(true)
    {
        cout << "send# ";
        string message;
        getline(cin, message);
        ssize_t s = send(sockfd, message.c_str(), message.size(), 0);
        if(s > 0)
        {
            char buffer[1024];
            ssize_t r = recv(sockfd, buffer, sizeof(buffer)-1, 0);
            if(r > 0)
            {
                buffer[r] = 0;
                cout << "recv: " << buffer << endl;
            }
            else 
            {
                break;
            }
        }
        else 
        {
            break;
        }
    }
    
    return 0;
}